package com.cash.app.application

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList

object ActivityLifecycleManager : Application.ActivityLifecycleCallbacks {

    private var currentActivityRef: WeakReference<Activity>? = null
    private var activityCount = 0

    private var isAppInForeground = false

    private val lifecycleListeners = CopyOnWriteArrayList<ActivityLifecycleListener>()

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(this)
    }

    fun getCurrentActivityContext(): Context? {
        return currentActivityRef?.get()?.takeIf { !it.isDestroyed && !it.isFinishing }
    }

    fun getSafeContext(): Context {
        val activity = currentActivityRef?.get()
        return if (activity != null && !activity.isDestroyed && !activity.isFinishing) {
            activity
        } else {
            getApplicationContext()
        }
    }

    fun getApplicationContext(): Context {
        return currentActivityRef?.get()?.applicationContext
            ?: throw IllegalStateException("ActivityLifecycleManager not initialized!")
    }

    fun isAppInForeground(): Boolean {
        return isAppInForeground
    }

    fun addLifecycleListener(listener: ActivityLifecycleListener) {
        lifecycleListeners.add(listener)
    }

    fun removeLifecycleListener(listener: ActivityLifecycleListener) {
        lifecycleListeners.remove(listener)
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        currentActivityRef = WeakReference(activity)
        lifecycleListeners.forEach { it.onActivityCreated(activity) }
    }

    override fun onActivityStarted(activity: Activity) {
        activityCount++
        updateForegroundStatus()
        currentActivityRef = WeakReference(activity)
        lifecycleListeners.forEach { it.onActivityStarted(activity) }
    }

    override fun onActivityResumed(activity: Activity) {
        currentActivityRef = WeakReference(activity)
        lifecycleListeners.forEach { it.onActivityResumed(activity) }
    }

    override fun onActivityPaused(activity: Activity) {
        lifecycleListeners.forEach { it.onActivityPaused(activity) }
    }

    override fun onActivityStopped(activity: Activity) {
        activityCount--
        updateForegroundStatus()
        lifecycleListeners.forEach { it.onActivityStopped(activity) }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityDestroyed(activity: Activity) {
        if (currentActivityRef?.get() == activity) {
            currentActivityRef = null
        }
        lifecycleListeners.forEach { it.onActivityDestroyed(activity) }
    }

    private fun updateForegroundStatus() {
        val wasInForeground = isAppInForeground
        isAppInForeground = activityCount > 0

        if (wasInForeground != isAppInForeground) {
            lifecycleListeners.forEach {
                if (isAppInForeground) {
                    it.onAppEnteredForeground()
                } else {
                    it.onAppEnteredBackground()
                }
            }
        }
    }

    interface ActivityLifecycleListener {
        fun onActivityCreated(activity: Activity) {}
        fun onActivityStarted(activity: Activity) {}
        fun onActivityResumed(activity: Activity) {}
        fun onActivityPaused(activity: Activity) {}
        fun onActivityStopped(activity: Activity) {}
        fun onActivityDestroyed(activity: Activity) {}
        fun onAppEnteredForeground() {}
        fun onAppEnteredBackground() {}
    }
}